package com.CmJava.tomcat.Server.service.container;

import com.CmJava.tomcat.Server.Component;
import com.CmJava.tomcat.Server.service.connector.Connector;
import com.CmJava.tomcat.Server.life.Lifecycle;
import com.CmJava.tomcat.Server.life.LifecycleState;
import com.CmJava.tomcat.Server.req_resp.HttpServletRequest;
import com.CmJava.tomcat.Server.req_resp.HttpServletResponse;


import java.io.IOException;
import java.io.OutputStream;
import java.util.Timer;
import java.util.TimerTask;

public class HttpServlet implements Lifecycle, Component {

    private LifecycleState lifecycleState = LifecycleState.NEW;
    private long deathTime;
    private Timer timer;

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws RuntimeException {
        try {
            response.getOutputStream().write((response.getResponseHeader() + "Hello!!").getBytes());
            response.getOutputStream().flush();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (response.getOutputStream() != null)
                    response.getOutputStream().close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws RuntimeException {
        doGet(request, response);
    }


    @Override
    public void init() {
        if (lifecycleState == LifecycleState.NEW) {
            lifecycleState = LifecycleState.INITIALIZED;
        }

        System.out.println("=========HttpServlet初始化成功，超时时间为2s=========");
    }

    @Override
    public void start() {
        if (timer == null) {
            timer = new Timer();
        }
        if (lifecycleState == LifecycleState.NEW) {
            init();
        } else if (lifecycleState == LifecycleState.STOPPING || lifecycleState == LifecycleState.IDELING) {
            lifecycleState = LifecycleState.INITIALIZED;
        } else if (lifecycleState == LifecycleState.DESTROYING) {
            //如果正在销毁,返回wrapper重新执行


        }

        if (lifecycleState == LifecycleState.INITIALIZED) {
            lifecycleState = LifecycleState.STARTING;
            HttpServletRequest request = Connector.request;
            HttpServletResponse response = Connector.response;

            deathTime = System.currentTimeMillis();
            try {
                switch (request.getMethod()) {
                    case "GET":
                        doGet(request, response);
                        if (System.currentTimeMillis() - deathTime >= 2000) {
                            System.out.println("=========HttpServlet的get请求超时，超时时间为2s=========");
                        }
                        break;
                    case "POST":
                        doPost(request, response);
                        if (System.currentTimeMillis() - deathTime >= 2000) {
                            System.out.println("=========HttpServlet的post请求超时，超时时间为2s=========");
                        }
                        break;
                }

                //response返回消息
                //。。。。。。。。。。

                //闲置将被销毁
                deathTime = System.currentTimeMillis();
                lifecycleState = LifecycleState.IDELING;
                canDestory();
            } catch (Exception e) {
                stop();
                System.out.println("=========HttpServlet出现未知错误=========");
                e.printStackTrace();
                erroResponse();
            }

        }
    }

    private void erroResponse() {
        OutputStream outputStream = Connector.response.getOutputStream();
        try {
            outputStream.write((Connector.response.getResponseHeader() + "erro!!").getBytes());
            outputStream.flush();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (outputStream != null)
                    outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void canDestory() {
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                if (System.currentTimeMillis() - deathTime >= 2000 && lifecycleState == LifecycleState.IDELING) {
                    System.out.println("=========HttpServlet的闲置时间超过2s，将被销毁=========");
                    destroy();
                }
            }
        }, 10, 500);
    }

    @Override
    public void stop() {
        lifecycleState = LifecycleState.STOPPING;
    }

    @Override
    public void destroy() {

        lifecycleState = LifecycleState.DESTROYING;
        Component component = Connector.container;
        while (true) {
            component = component.getChild();
            if (component instanceof Wrapper) {
                break;
            }
        }
        component.setChild(null);
        timer.cancel();
        timer = null;
        System.gc();
    }

    @Override
    public LifecycleState getState() {
        return this.lifecycleState;
    }

    @Override
    public Component getChild() {
        return null;
    }

    @Override
    public void setChild(Component child) {

    }


}
